<script setup>
import {ref, onMounted, watch, nextTick} from 'vue';
import {
  Box,
  // Cube, 移除此行
  Collection,
  Document // 添加这个作为替代
} from '@element-plus/icons-vue'

import axios from "axios";
import {ElMessage, ElMessageBox} from "element-plus";
import {router} from "@/router/index.js";

// 原始数据
const shippingData = ref([])
const dialogVisible = ref(false) // 控制弹窗显示
// 地图相关
const showMapDialog = ref(false);
const selectedShipping = ref(null);
const mapInstance = ref(null); // 百度地图实例
// 模板选项数据
const templateOptions = [
  {
    type: 1,
    title: '重量模板',
    description: '按商品重量计算运费',
    icon: Box
  },
  {
    type: 2,
    title: '体积模板',
    description: '按商品体积计算运费',
    icon: Document // 使用 Document 替代 Cube
  },
  {
    type: 3,
    title: '件数模板',
    description: '按商品件数计算运费',
    icon: Collection
  }
]

// 获取模板类型名称
const getTemplateTypeName = (status) => {
  const types = {
    1: '按重量计费',
    2: '按体积计费',
    3: '按件数计费'
  }
  return types[status] || '运费模板'
}

const initData = () => {
  axios.get(`/shippingTemplate/getAllData`).then(res => {
    shippingData.value = res.data
  })
}

// 初始化地图
const initBaiduMap = () => {
  // 检查是否已加载百度地图API
  if (!window.BMap) {
    // 动态加载百度地图API
    const script = document.createElement('script')
    script.src = `https://api.map.baidu.com/api?v=3.0&ak=bUc4Ati12KarFSZENaMdK2m7XfP56T39&callback=initBaiduMapCallback`
    document.head.appendChild(script)

    // 设置回调函数
    window.initBaiduMapCallback = () => {
      // 确保地图容器存在
      if (!document.getElementById('map-container')) {
        return
      }
      // 再次调用初始化
      doInitBaiduMap()
    }
    return
  }

  doInitBaiduMap()
}

// 实际的百度地图初始化逻辑
const doInitBaiduMap = () => {
  const provinces = [];

  selectedShipping.value.templates.forEach(template => {
    try {
      // 如果是字符串格式的 JSON 或者逗号分隔的字符串，就解析它
      let destinations;
      if (typeof template.destination === 'string') {
        // 先尝试解析 JSON 格式
        try {
          destinations = JSON.parse(template.destination);
        } catch (jsonError) {
          // 如果不是有效的 JSON，则按逗号分隔符分割字符串
          destinations = template.destination.split(',').map(s => s.trim());
        }
      } else {
        destinations = template.destination;
      }

      // 确保是数组
      if (Array.isArray(destinations)) {
        destinations.forEach(d => {
          // 如果 d 是对象且有 province 属性，则直接使用 province 值
          if (typeof d === 'object' && d.province) {
            provinces.push(d.province);
          } else if (typeof d === 'string') { // 如果 d 是字符串，则直接作为省份名
            provinces.push(d);
          }
        });
      } else if (destinations && typeof destinations === 'string') {
        // 如果是单个字符串而不是数组
        provinces.push(destinations);
      }
    } catch (e) {
      console.error('JSON 解析失败:', template.destination);
    }
  });

  console.log('要高亮的省份:', [...new Set(provinces)]); // 去重输出

  // 创建地图实例
  mapInstance.value = new BMap.Map("map-container");
  const point = new BMap.Point(116.404, 39.915);
  mapInstance.value.centerAndZoom(point, 4);

  const bdary = new BMap.Boundary();

  // 去重后的省份列表
  [...new Set(provinces)].forEach(province => {
    bdary.get(province, function(result) {
      if (result && result.boundaries && result.boundaries.length > 0) {
        const count = result.boundaries.length;
        for (let i = 0; i < count; i++) {
          const ply = new BMap.Polygon(result.boundaries[i], {
            strokeColor: "#FF0000",
            strokeWeight: 2,
            fillColor: "#FFAAAA",
            fillOpacity: 0.4
          });
          mapInstance.value.addOverlay(ply);
        }
      } else {
        console.warn(`未找到省份 "${province}" 的边界数据`);
      }
    });
  });

  mapInstance.value.enableScrollWheelZoom(true);
};
// 监听弹窗打开事件
watch(showMapDialog, (newValue) => {
  if (newValue) {
    // 确保地图容器已渲染
    nextTick(() => {
      initBaiduMap();
    });
  } else {
    // 关闭弹窗时清理地图实例
    if (mapInstance.value) {
      mapInstance.value = null;
    }
  }
});
const handleAddTemplate = () => {
  dialogVisible.value = true // 显示弹窗
}

// 添加新模板
const addNewTemplate = (type) => {
  dialogVisible.value = false
  router.push(`addShippingTemplate?status=${type}`)
}

const handleCopyTemplate = (template) => {
  console.log(`复制${getTemplateTypeName(template.status)}模板`)
  // 复制模板逻辑
}

const handleEditTemplate = (template) => {
  console.log(`修改${getTemplateTypeName(template.status)}模板`)
  // 修改模板逻辑
}

const handleDeleteTemplate = (template) => {
  ElMessageBox.confirm('确定要删除该模板吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    axios.delete(`/shippingTemplate/deleteShippingById/${template.id}`).then((res) => {
      initData()
      ElMessage.success(res.data)
    })

  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}
// 新增的方法
const handleShowMapByRow = (row) => {
  selectedShipping.value = {
    id: row.id,
    templateName: row.templateName || '未知模板',
    templates: [row]
  };
  showMapDialog.value = true;
};
onMounted(()=>{
  initData()
})
</script>

<template>
  <div class="shipping-template-container">
    <!-- 顶部导航区域 -->
    <div class="top-navigation">
      <!-- 面包屑导航 -->
      <div class="breadcrumb-container">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>商城系统</el-breadcrumb-item>
          <el-breadcrumb-item>运费模板</el-breadcrumb-item>
        </el-breadcrumb>
      </div>

      <!-- 标题和操作按钮 -->
      <div class="header-container">
        <h2 class="page-title">运费模板</h2>
        <div class="header-actions">
          <el-button type="primary" class="add-btn" @click="handleAddTemplate">
            <el-icon><Plus /></el-icon>
            添加模板
          </el-button>
        </div>
      </div>
    </div>

    <!-- 模板卡片容器 -->
    <div class="cards-container">
      <el-dialog
          v-model="showMapDialog"
          title="配送省份地图"
          width="80%"
          class="map-dialog"
      >
        <div id="map-container" style="width: 100%; height: 600px;"></div>
      </el-dialog>
      <!-- 动态渲染每个运费模板 -->
      <el-card
          v-for="shipping in shippingData"
          :key="shipping.id"
          class="template-card"
          shadow="hover"
      >
        <div class="template-header">
          <div class="template-info">
            <span class="template-name">{{ shipping.templateName }}</span>
            <span class="edit-time">最近编辑时间：{{ shipping.updateTime || '2019-04-11 15:36' }}</span>
          </div>
          <div class="template-actions">
            <el-button type="primary" plain size="small" @click="handleCopyTemplate(shipping)">复制模板</el-button>
            <el-button type="primary" plain size="small" @click="handleEditTemplate(shipping)">修改</el-button>
            <el-button type="danger" plain size="small" @click="handleDeleteTemplate(shipping)">删除</el-button>
          </div>
        </div>

        <!-- 统一展示所有运费规则 -->
        <el-table
            :data="shipping.templates"
            border
            class="shipping-table"
            :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
        >
          <el-table-column prop="expressCompany" label="物流公司" width="150" align="center" />
          <el-table-column prop="destination" label="运送到" width="200" align="center" />
          <el-table-column label="计费类型" width="120" align="center">
            <template #default="{row}">
              <span>{{ getTemplateTypeName(row.status) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="基础费用" width="120" align="center">
            <template #default="{row}">
              <span class="price">
                {{
                  row.status === 1 ? row.low :
                      row.status === 2 ? row.volume :
                          row.amount
                }}元
              </span>
            </template>
          </el-table-column>
          <el-table-column label="中间费用" width="150" align="center" v-if="shipping.templates.some(t => t.status === 1)">
            <template #default="{row}">
              <span class="price" v-if="row.status === 1">{{ row.mid }}元</span>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column label="高端费用" width="150" align="center" v-if="shipping.templates.some(t => t.status === 1)">
            <template #default="{row}">
              <span class="price" v-if="row.status === 1">{{ row.high }}元</span>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column label="附加费用" width="180" align="center">
            <template #default="{row}">
              <span class="price">
                {{
                  row.status === 1 ? row.addWeight :
                      row.status === 2 ? row.addVolume :
                          row.addAmount
                }}元
              </span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120" align="center">
            <template #default="{row}">
              <el-tooltip content="查看该行配送区域地图" placement="top">
                <el-button size="small" @click="handleShowMapByRow(row)">查看地图</el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>

    <el-dialog
        v-model="dialogVisible"
        title="选择模板类型"
        width="400px"
        center
        class="template-dialog"
    >
      <div class="dialog-content">
        <div class="template-options">
          <div
              v-for="option in templateOptions"
              :key="option.type"
              class="template-option"
              @click="addNewTemplate(option.type)"
          >
            <el-icon class="option-icon"><component :is="option.icon" /></el-icon>
            <div class="option-text">
              <h4 class="option-title">{{ option.title }}</h4>
              <p class="option-desc">{{ option.description }}</p>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>

  </div>
</template>

<style scoped>
.shipping-template-container {
  padding: 20px 24px;
  max-width: 1200px;
  margin: 0 auto;
  background-color: #f8f9fa;
  min-height: 100vh;
}

/* 顶部导航区域 */
.top-navigation {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  margin-bottom: 24px;
  padding: 16px 20px;
}

/* 面包屑导航 */
.breadcrumb-container {
  margin-bottom: 16px;
  padding: 8px 0;
}

.breadcrumb-container :deep(.el-breadcrumb) {
  font-size: 14px;
}

.breadcrumb-container :deep(.el-breadcrumb__inner) {
  color: #606266;
  font-weight: normal;
}

.breadcrumb-container :deep(.el-breadcrumb__item:last-child .el-breadcrumb__inner) {
  color: #303133;
  font-weight: 500;
}

/* 标题区域 */
.header-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.page-title {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #303133;
  line-height: 1.5;
}

.header-actions {
  display: flex;
  align-items: center;
}

.add-btn {
  padding: 8px 16px;
  height: 36px;
}

/* 模板卡片容器 */
.cards-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.template-card {
  border-radius: 8px;
  border: 1px solid #ebeef5;
  transition: all 0.3s;
}

.template-card:hover {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.template-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 16px;
  margin-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.template-info {
  display: flex;
  flex-direction: column;
}

.template-name {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
}

.edit-time {
  font-size: 13px;
  color: #909399;
}

.template-actions {
  display: flex;
  gap: 8px;
}

.shipping-table {
  margin-top: 16px;
  font-size: 14px;
}

.shipping-table :deep(.el-table__header) th {
  font-weight: 600;
}

.price {
  color: #409eff;
  font-weight: 500;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header-container {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }

  .header-actions {
    width: 100%;
    justify-content: flex-end;
  }

  .template-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }

  .template-actions {
    width: 100%;
    justify-content: flex-end;
  }
}


.template-dialog :deep(.el-dialog__header) {
  border-bottom: 1px solid #f0f0f0;
  margin-right: 0;
}

.template-dialog :deep(.el-dialog__title) {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.dialog-content {
  padding: 10px 20px;
}

.template-options {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.template-option-btn {
  height: 100px; /* 固定高度 */
  width: 100%; /* 宽度自适应容器 */
  padding: 0; /* 移除内边距，使用内部元素控制间距 */
  border-radius: 8px;
  transition: all 0.3s;
  display: flex;
  align-items: center;
  justify-content: center;
}

.template-option-btn:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.option-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  padding: 15px;
}

.option-text {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
}

.option-icon {
  font-size: 28px;
  margin-bottom: 8px;
  color: var(--el-color-primary);
  flex-shrink: 0; /* 防止图标被压缩 */
}

.option-title {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 4px;
  text-align: center;
  width: 100%;
}

.option-desc {
  font-size: 12px;
  color: #909399;
  text-align: center;
  width: 100%;
}

/* 确保所有按钮内容严格对齐 */
.template-option-btn {
  height: 100px;
  width: 100%;
  padding: 0;
}

.template-options {
  display: flex;
  flex-direction: column;
  gap: 15px;
  align-items: center; /* 新增：确保所有选项水平居中 */
}

/* 响应式调整 */
@media (max-width: 768px) {
  .template-dialog {
    width: 90% !important;
  }

  .template-option-btn {
    height: 90px; /* 移动端稍小的高度 */
  }
}

.template-option {
  display: flex;
  align-items: center;
  padding: 15px;
  margin-bottom: 10px;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
  width: 100%;
}

.template-option:hover {
  border-color: var(--el-color-primary);
  background-color: #f5f7fa;
}

.option-icon {
  font-size: 24px;
  margin-right: 15px;
  color: var(--el-color-primary);
  flex-shrink: 0;
}

.option-text {
  flex-grow: 1;
}

.option-title {
  font-size: 16px;
  font-weight: 600;
  margin: 0 0 5px 0;
  color: #303133;
  text-align: left;
}

.option-desc {
  font-size: 14px;
  margin: 0;
  color: #606266;
  text-align: left;
}

/* 最后一个选项去掉底部边距 */
.template-option:last-child {
  margin-bottom: 0;
}

/* 确保所有选项对齐 */
.template-options {
  display: flex;
  flex-direction: column;
  align-items: stretch;
}
.map-dialog .el-dialog__body {
  padding: 0;
}
#map-container {
  border-radius: 4px;
}
</style>